<?php
namespace App\Controllers;
use Framework\Database;
use Framework\Validation;
use Framework\Session;
class UserController{
    protected $db;
    public function _construct()
    {
        $config = require basePath('config/db.php');$this->db = new Database($config);
    }
/**
 * @return void
 */
    public function login()
    {

        loadView('users/login');
    }
    /**
     * @return void
     */
    public function create()
    {
        loadView('users/create');
    }
    /**
     * 将用户数据存储在数据库中
     * @return void
     */
    public function store()
    {
        $name =$_PoST['name'];
        $email = $ PosT['email'];
        $city =$ PosT['city'];
        $province =$ PosT['province'];
        $password =$ POST['password'];
        $passwordconfirmation =$PosT['password confirmation'];
        $errors=[];
        if(!Validation::email($email)){
            $errors['email']='请输入一个合法的电子邮箱地址!';
        }
        if(!Validation::string($name,2，50)){
            $errors['name']='姓名长度为2到58!':
        }
        if(!Validation::string($password，6，50)){
            $errors['password']='密码长度为至少6位!';
        }
        if(!Validation::match($password, $passwordConfirmation)){
            $errors['password confirmation']='两次的输入密码不一致!'
        }
        if(!empty($errors)){
        loadView('users/create',[
            'errors'=> $errors,
            'user' =>[
            'name'=>$name,
            'email'=> $email,
            'city'=> $city,
            'province'=>$province,
            ]
        ]);
        exit;
        }else{
            $params=[
                'email'=> $email
            ];
            $user = $this->db->query('SELECT * FROM users WHERE email:email',$params)->fetch();
            if($user){
                $errors['email']='该邮箱已注册!';
                loadView('users/create',[
                    'errors' => $errors
                ]);
                exit;
             
        }
        $params =[
            'name'=> $name,
            'email'=> $email,
            'city'=> $city,// 城市
            'province'=>$province,//州
            'password'=> password_hash($password, PASSWORD DEFAULT)
        ];
        $this->db->query('INSERT INT0 users (name, email, city, province, password) VALUEs (:name, :email, :city,:province,:password)',$params);
        $userId = $this->db->conn->lastInsertId();
        Session::set('user',[
            'id'=> $userId,
            'name'=> $name,
            'email'=> $email,
            'city'=> $city,
            'province'=> $province1
        ]);


        redirect('/');
        }
    }
    /**
     * @return void
     * 
     */
    public function logout()
    {
        Session::clearAll();
        $params = session_get_cookie_params();
        setcookie('PHPSESSID','',time()-86400,$params['path'],$params['domain']);
        redirect('/');
    }
}
